package com.zl.learning.io.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AsynchronousFileChannelTest {
    static Thread current;

    public static void main(String[] args) {
        long size = 0;
        Path path = Paths.get("D:", "新建文本文档.txt");
        try {
            size = Files.size(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(size);
        ByteBuffer buffer = ByteBuffer.allocate((int) size);
        try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
            current = Thread.currentThread();
            asynchronousFileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    attachment.flip();
                    String val = Charset.forName("GBK").decode(attachment).toString();
                    System.out.println(val);
                    System.out.println();
                    System.out.println(attachment);
                    System.out.print("Read bytes: " + result);
                    attachment.clear();
                    current.interrupt();
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.out.println(attachment);
                    System.out.println("Error:" + exc);
                    current.interrupt();
                }
            });
            System.out.println("Waiting for reading operation to end ...");
            try {
                current.join();
            } catch (InterruptedException ignored) {

            }
//now the buffer contains the read bytes
            System.out.println("Close everything and leave! Bye, bye ...");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
